package com.cqw.commontest.thread.unit2;

import java.util.concurrent.TimeUnit;

/**
 * @Author: caoqingwen
 * @CreateTime: 2021-06-04 16:14
 * @Description: Thread常用api
 */
public class Test5 {

    private static final Object lock = new Object();


    public static void main(String[] args) {
        //每隔一秒钟打印AB
        new Thread(new PrintA(lock)).start();
        new Thread(new PrintB(lock)).start();
    }


}


class PrintA implements Runnable {


    private Object lock;

    public PrintA(Object lock) {
        this.lock = lock;
    }

    @Override
    public void run() {
        synchronized (lock) {
            while (true){
                try {
                    TimeUnit.SECONDS.sleep(1);
                    System.out.println("===========A");
                    lock.notify();
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

class PrintB implements Runnable {

    private Object lock;

    public PrintB(Object lock) {
        this.lock = lock;
    }

    @Override
    public void run() {
        synchronized (lock) {
            while (true){
                try {
                    TimeUnit.SECONDS.sleep(1);
                    System.out.println("===========B");
                    lock.notify();
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
